package com.diligent.cloud.sfc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.diligent.cloud.sfc.model.OAuthTokenCheck;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.annotation.RequestScope;

import javax.servlet.http.HttpServletRequest;

@Component
public class OauthConfig {

    @Value("${oauth.check_token}")
    private String checkUrl;

    @Autowired
    private RestTemplate restTemplate;

    public OAuthTokenCheck checkToken(String token) {
        try {
            ResponseEntity responseEntity = restTemplate.getForEntity(checkUrl + "?token=" + token, String.class);
            String body = (String) responseEntity.getBody();
            JSONObject jsonObject = (JSONObject) JSONObject.parse(body);
            OAuthTokenCheck authTokenCheck = JSON.toJavaObject(jsonObject, OAuthTokenCheck.class);
            if (authTokenCheck != null && authTokenCheck.getUser_name() != null) {
                return authTokenCheck;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    @RequestScope
    @Bean
    RequestParams requestParams(HttpServletRequest request) {
        return new RequestParams(request, this);
    }

    @Data
    public static class RequestParams {
        private Long systemId;
        private Long companyId;

        public RequestParams(HttpServletRequest request, OauthConfig oauthConfig) {
            try {
                String token = getToken(request);
                if (token != null) {
                    OAuthTokenCheck authTokenCheck = oauthConfig.checkToken(token);
                    if (authTokenCheck.getSystem_id() != null) {
                        Long systemId = Long.parseLong(authTokenCheck.getSystem_id());
                        this.systemId = systemId;
                    }
                    if (authTokenCheck.getOrg_id() != null) {
                        Long companyId = Long.parseLong(authTokenCheck.getOrg_id());
                        this.companyId = companyId;
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("", e);
            }
        }

        private String getToken(HttpServletRequest request) {
            String header = request.getHeader("Authorization");
            String token = StringUtils.substringAfter(header, "Bearer ");
            return token;
        }
    }
}
